import requests
import json
from datetime import datetime
from mcp.server.fastmcp import FastMCP

# 创建MCP服务器实例
mcp = FastMCP(name="MyCustomTools", host="0.0.0.0", port=8001, log_level="INFO")

@mcp.tool(description="Get the current date and time")
def get_current_time() -> str:
    """Get the current date and time"""
    current_time = datetime.now()
    return f"Current time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}"


@mcp.tool(name="get_current_goods", description="Get current goods list from the management system")
def get_current_goods(page_number: int = 1, page_size: int = 10, sort: str = "create_time", order: str = "desc",
                      store_id: str = "1758013959") -> str:
    """Get current goods list with pagination and sorting"""
    url = "https://ghs-fwzx-test.9free.com.cn:1443/manager-api/manager/goods/goods/list"

    # 设置请求头
    headers = {
        "accesstoken": "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyQ29udGV4dCI6IntcInVzZXJuYW1lXCI6XCJhZG1pblwiLFwibmlja05hbWVcIjpcIui2hee6p-euoeeQhuWRmFwiLFwiZmFjZVwiOlwiaHR0cHM6Ly9maWxlcy5zeDE3ODguY24vZHRzLzc2NzU1NGRmZmE0YjRlMWM4NDk4NjBmNTJhYThjODk3LmpwZWdcIixcImlkXCI6XCIxMzM3MzA2MTEwMjc3NDc2MzUyXCIsXCJsb25nVGVybVwiOmZhbHNlLFwicm9sZVwiOlwiTUFOQUdFUlwiLFwiaXNTdXBlclwiOnRydWV9Iiwic3ViIjoiYWRtaW4iLCJleHAiOjE3NTgwMjEzMDh9.ypSClKKJ0FweeBJ2etbXwuemREYRpNUDg_OLmJJb74M",
        "Content-Type": "application/json"
    }

    # 设置请求参数
    params = {
        "pageNumber": page_number,
        "pageSize": page_size,
        "sort": sort,
        "order": order
    }

    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()  # 检查HTTP错误

        data = response.json()

        # 提取关键信息
        if 'records' in data:
            goods_list = []
            for item in data['records']:
                goods_info = {
                    'id': item.get('id'),
                    'name': item.get('goodsName'),
                    'price': item.get('price'),
                    'store_name': item.get('storeName'),
                    'market_enable': item.get('marketEnable'),
                    'quantity': item.get('quantity'),
                    'goods_type': item.get('goodsType')
                }
                goods_list.append(
                    f"商品ID: {goods_info['id']}, 名称: {goods_info['name']}, 价格: {goods_info['price']}, 店铺: {goods_info['store_name']}, 状态: {goods_info['market_enable']}, 库存: {goods_info['quantity']}")

            total = data.get('total', 0)
            current_page = data.get('current', 1)
            total_pages = data.get('pages', 1)

            result = f"商品列表 (第{current_page}页/共{total_pages}页, 总计{total}个商品):\n" + "\n".join(goods_list)
            return result
        else:
            return "未找到商品数据"

    except requests.exceptions.RequestException as e:
        return f"获取商品列表失败: {str(e)}"


if __name__ == "__main__":
    mcp.run(transport='streamable-http')
